<template>
  <view class="system-message-page">
    <!-- 自定义导航栏 -->
    <nav-bar title="系统通知" :show-back="true"></nav-bar>
    
    <!-- 通知类型切换 -->
    <view class="tab-switch">
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        全部
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'system' }"
        @click="switchTab('system')"
      >
        系统
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'activity' }"
        @click="switchTab('activity')"
      >
        活动
      </view>
    </view>
    
    <!-- 通知列表 -->
    <scroll-view 
      class="message-list"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="notifications.length > 0">
        <view
          v-for="item in filteredNotifications"
          :key="item.id"
          class="message-item"
          :class="{ 'unread': !item.isRead }"
          @click="viewNotificationDetail(item)"
        >
          <view class="message-dot" v-if="!item.isRead"></view>
          <view class="message-icon" :class="getIconClass(item.type)">
            <tn-icon :name="getIconName(item.type)" size="36" color="#ffffff"></tn-icon>
          </view>
          <view class="message-content">
            <view class="message-title">{{ item.title }}</view>
            <view class="message-text">{{ item.content }}</view>
            <view class="message-footer">
              <text class="message-time">{{ formatNotificationTime(item.time) }}</text>
              <text class="message-action" v-if="item.actionText" @click.stop="handleAction(item)">
                {{ item.actionText }}
              </text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无数据状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty-notification.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无通知消息</text>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="hasMore && filteredNotifications.length > 0">
        <tn-loading mode="circle" size="24"></tn-loading>
        <text>加载更多...</text>
      </view>
      
      <view class="no-more" v-if="!hasMore && filteredNotifications.length > 0">
        <text>没有更多通知了</text>
      </view>
    </scroll-view>
    
    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="read-all-btn" @click="markAllAsRead">全部已读</button>
    </view>
    
    <!-- 通知详情弹窗 -->
    <tn-popup v-model:show="showDetail" mode="center">
      <view class="detail-popup">
        <view class="popup-header">
          <text class="popup-title">{{ currentNotification.title }}</text>
          <view class="close-btn" @click="showDetail = false">
            <tn-icon name="close" size="36"></tn-icon>
          </view>
        </view>
        <view class="popup-content">
          <view class="popup-time">{{ formatNotificationTime(currentNotification.time) }}</view>
          <view class="popup-text">{{ currentNotification.content }}</view>
          <view class="popup-image" v-if="currentNotification.image">
            <image :src="currentNotification.image" mode="widthFix"></image>
          </view>
        </view>
        <view class="popup-footer" v-if="currentNotification.actionText">
          <button class="action-btn" @click="handleAction(currentNotification)">
            {{ currentNotification.actionText }}
          </button>
        </view>
      </view>
    </tn-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import NavBar from '@/components/navbar/NavBar.vue';

// 当前选中的标签
const activeTab = ref('all');

// 通知列表
const notifications = ref([]);

// 刷新加载相关
const isRefreshing = ref(false);
const hasMore = ref(true);

// 详情弹窗
const showDetail = ref(false);
const currentNotification = ref({});

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
};

// 获取过滤后的通知
const filteredNotifications = computed(() => {
  if (activeTab.value === 'all') {
    return notifications.value;
  }
  return notifications.value.filter(item => item.type === activeTab.value);
});

// 获取图标名称
const getIconName = (type) => {
  const iconMap = {
    'system': 'notification',
    'activity': 'flag',
    'reward': 'wallet',
    'idle': 'tag',
    'comment': 'comment'
  };
  return iconMap[type] || 'notification';
};

// 获取图标样式类名
const getIconClass = (type) => {
  return `icon-${type}`;
};

// 格式化通知时间
const formatNotificationTime = (time) => {
  const notificationDate = new Date(time);
  const now = new Date();
  
  // 今天的消息只显示时间
  if (notificationDate.toDateString() === now.toDateString()) {
    return notificationDate.getHours().toString().padStart(2, '0') + ':' + 
           notificationDate.getMinutes().toString().padStart(2, '0');
  }
  
  // 昨天的消息显示"昨天"
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (notificationDate.toDateString() === yesterday.toDateString()) {
    return '昨天';
  }
  
  // 今年的消息显示"月-日"
  if (notificationDate.getFullYear() === now.getFullYear()) {
    return (notificationDate.getMonth() + 1).toString().padStart(2, '0') + '-' + 
           notificationDate.getDate().toString().padStart(2, '0');
  }
  
  // 往年的消息显示"年-月-日"
  return notificationDate.getFullYear() + '-' + 
         (notificationDate.getMonth() + 1).toString().padStart(2, '0') + '-' + 
         notificationDate.getDate().toString().padStart(2, '0');
};

// 查看通知详情
const viewNotificationDetail = (notification) => {
  // 设置当前查看的通知
  currentNotification.value = notification;
  showDetail.value = true;
  
  // 标记为已读
  if (!notification.isRead) {
    markAsRead(notification.id);
  }
};

// 标记通知为已读
const markAsRead = (id) => {
  const index = notifications.value.findIndex(item => item.id === id);
  if (index !== -1) {
    notifications.value[index].isRead = true;
    
    // 实际项目中应该调用API标记已读
    console.log('标记通知已读:', id);
  }
};

// 标记所有通知为已读
const markAllAsRead = () => {
  notifications.value.forEach(item => {
    item.isRead = true;
  });
  
  // 实际项目中应该调用API标记所有已读
  uni.showToast({
    title: '全部标记为已读',
    icon: 'success'
  });
};

// 处理通知相关操作
const handleAction = (notification) => {
  console.log('执行通知操作:', notification);
  
  // 根据不同类型的通知执行不同操作
  switch (notification.type) {
    case 'system':
      // 系统通知操作
      break;
    case 'activity':
      // 活动通知操作，如跳转到活动详情页
      uni.navigateTo({
        url: `/pages/activity/detail?id=${notification.relatedId}`
      });
      break;
    case 'reward':
      // 赏金任务通知操作，如跳转到赏金任务详情页
      uni.navigateTo({
        url: `/pages/detail/reward-detail?id=${notification.relatedId}`
      });
      break;
    case 'idle':
      // 闲置物品通知操作，如跳转到闲置物品详情页
      uni.navigateTo({
        url: `/pages/detail/idle-detail?id=${notification.relatedId}`
      });
      break;
    case 'comment':
      // 评论通知操作，如跳转到帖子详情页
      uni.navigateTo({
        url: `/pages/detail/post-detail?id=${notification.relatedId}`
      });
      break;
    default:
      break;
  }
  
  // 关闭详情弹窗
  showDetail.value = false;
};

// 加载更多通知
const loadMore = () => {
  if (!hasMore.value) return;
  
  console.log('加载更多通知');
  
  // 实际项目中应该调用API加载更多通知
  // 模拟加载
  setTimeout(() => {
    if (notifications.value.length >= 20) {
      hasMore.value = false;
      return;
    }
    
    const newNotifications = [
      {
        id: notifications.value.length + 1,
        type: 'system',
        title: '系统维护通知',
        content: `系统将于今晚22:00-23:00进行维护升级，期间可能无法正常使用部分功能，敬请谅解。这是第${notifications.value.length + 1}条加载的通知。`,
        time: new Date(new Date().getTime() - (notifications.value.length + 1) * 86400000),
        isRead: false
      }
    ];
    
    notifications.value = [...notifications.value, ...newNotifications];
  }, 1000);
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  
  // 实际项目中应该调用API刷新通知列表
  console.log('刷新通知列表');
  
  // 模拟刷新完成
  setTimeout(() => {
    isRefreshing.value = false;
    
    // 模拟新通知
    const newNotification = {
      id: Date.now(),
      type: 'system',
      title: '新的系统公告',
      content: '感谢使用星遇App，我们刚刚上线了新的功能，快去体验吧！',
      time: new Date(),
      isRead: false
    };
    
    notifications.value = [newNotification, ...notifications.value];
  }, 1000);
};

// 初始化通知列表
const initNotifications = () => {
  // 模拟通知数据
  notifications.value = [
    {
      id: 1,
      type: 'system',
      title: '欢迎使用星遇App',
      content: '欢迎加入星遇大家庭，这里是大学生的专属社交平台，希望你能在这里结交到志同道合的朋友！',
      time: new Date(new Date().getTime() - 3600000 * 24 * 2), // 2天前
      isRead: true
    },
    {
      id: 2,
      type: 'activity',
      title: '新活动上线：校园歌手大赛',
      content: '校园歌手大赛报名开始啦！只要你热爱唱歌，就来参加吧！丰厚奖品等你来拿！',
      time: new Date(new Date().getTime() - 3600000 * 12), // 12小时前
      isRead: false,
      actionText: '查看详情',
      relatedId: 1,
      image: 'https://picsum.photos/id/96/400/200'
    },
    {
      id: 3,
      type: 'reward',
      title: '你发布的赏金任务已被接单',
      content: '你发布的赏金任务"帮取快递"已被用户"张同学"接单，请及时关注任务进展。',
      time: new Date(new Date().getTime() - 3600000 * 5), // 5小时前
      isRead: false,
      actionText: '查看任务',
      relatedId: 1
    },
    {
      id: 4,
      type: 'idle',
      title: '你的闲置物品有新留言',
      content: '你发布的闲置物品"9成新 iPad Pro"有新的留言，快去看看吧！',
      time: new Date(new Date().getTime() - 3600000 * 2), // 2小时前
      isRead: false,
      actionText: '查看物品',
      relatedId: 1
    },
    {
      id: 5,
      type: 'comment',
      title: '你的帖子有新评论',
      content: '用户"星遇用户2"评论了你的帖子"学校食堂的饭太好吃了"：在哪个食堂啊，说详细点呗！',
      time: new Date(new Date().getTime() - 1800000), // 30分钟前
      isRead: false,
      actionText: '查看评论',
      relatedId: 1
    }
  ];
};

onMounted(() => {
  // 初始化通知列表
  initNotifications();
});
</script>

<style lang="scss" scoped>
.system-message-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.tab-switch {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 20rpx;
  
  .tab-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60rpx;
    font-size: 28rpx;
    color: #666666;
    position: relative;
    
    &.active {
      color: #32C5FF;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #32C5FF;
        border-radius: 4rpx;
      }
    }
  }
}

.message-list {
  flex: 1;
  padding: 0 20rpx;
}

.message-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  position: relative;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  
  &.unread {
    background: linear-gradient(to right, rgba(50, 197, 255, 0.05), #ffffff);
  }
  
  .message-dot {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 16rpx;
    height: 16rpx;
    background-color: #FF5252;
    border-radius: 50%;
  }
  
  .message-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 20rpx;
    flex-shrink: 0;
    
    &.icon-system {
      background-color: #32C5FF;
    }
    
    &.icon-activity {
      background-color: #76FF03;
    }
    
    &.icon-reward {
      background-color: #BA68C8;
    }
    
    &.icon-idle {
      background-color: #FF9800;
    }
    
    &.icon-comment {
      background-color: #2196F3;
    }
  }
  
  .message-content {
    flex: 1;
    overflow: hidden;
    
    .message-title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      color: #333333;
    }
    
    .message-text {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.5;
      margin-bottom: 16rpx;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .message-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .message-time {
        font-size: 24rpx;
        color: #999999;
      }
      
      .message-action {
        font-size: 24rpx;
        color: #32C5FF;
        padding: 4rpx 12rpx;
        background-color: rgba(50, 197, 255, 0.1);
        border-radius: 20rpx;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 250rpx;
    height: 250rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999999;
  }
}

.loading-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  font-size: 24rpx;
  color: #999999;
  
  text {
    margin-left: 10rpx;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.05);
  
  .read-all-btn {
    width: 100%;
    height: 80rpx;
    background: linear-gradient(135deg, #32C5FF, #BA68C8);
    color: #ffffff;
    border-radius: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30rpx;
    
    &::after {
      border: none;
    }
  }
}

.detail-popup {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  
  .popup-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      flex: 1;
      padding-right: 20rpx;
    }
    
    .close-btn {
      padding: 10rpx;
      color: #999999;
    }
  }
  
  .popup-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
    
    .popup-time {
      font-size: 24rpx;
      color: #999999;
      margin-bottom: 20rpx;
    }
    
    .popup-text {
      font-size: 28rpx;
      line-height: 1.6;
      color: #333333;
      margin-bottom: 20rpx;
    }
    
    .popup-image {
      width: 100%;
      margin-top: 20rpx;
      
      image {
        width: 100%;
        border-radius: 8rpx;
      }
    }
  }
  
  .popup-footer {
    padding: 20rpx 30rpx 30rpx;
    
    .action-btn {
      width: 100%;
      height: 80rpx;
      background: linear-gradient(135deg, #32C5FF, #BA68C8);
      color: #ffffff;
      border-radius: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
      
      &::after {
        border: none;
      }
    }
  }
}
</style> 